
var mysql = require('mysql');

var pool = null;

function getPool() {
  try {
    var pool = mysql.createPool({
      host: '127.0.0.1',
      port: "3306",
      user: 'root',
      password: '123',
      database: 'flutter_demo',
      connectionLimit: 100,//连接限制
      queueLimit: 0//最大连接等待数(0为不限制)
    });//创建一个pool连接池
    return pool;
  } catch (e) {
    console.log(e)
    return null;
  }
}




async function getConnection() {
  let connection = await new Promise((resolve, reject) => {
    try {
      pool.getConnection(function (err, connection) {
        if (err) {
          reject(err);
        }
        resolve(connection)
      });//获取
    } catch (e) {
      reject();
      console.log("error===", e)
    }
  });
  return connection;
}



exports.queryOne = async function (sql, params) {
  let res = await this.query(sql, params);
  if (res.length > 0) {
    return res[0];
  } else {
    return null;
  }
}

exports.query = async function (sql, params) {
  try {
    if (pool === null) {
      pool = getPool();
    }
    let connection;

    connection = await getConnection();
    let res = await new Promise((resolve, reject) => {
      connection.query(sql, params, function (err, result) {
        if (err) {
          console.log('[INSERT ERROR] - ', err.message);
          reject(err);
          return;
        }
        resolve(result)
      });
    })

    connection.release();

    // pool.releaseConnection(connection);
    return res;
  } catch (e) {
    console.error(e);
  }
}

exports.getConnection = async function () {
  return new Promise((resolve, reject) => {
    pool.getConnection(function (err, connection) {
      if (err) {
        reject(err);
      }
      resolve(connection)
    });//获取
  });
}